<template>
  <div id="monitoring">
    <div class="df" style="width: 100%">
      <div>
        <div class="chart-title">{{ chartsData.req.title }}</div>
        <areachart :chartsData="chartsData" ref="areachartRef" />
      </div>
      <div>
        <div class="chart-title">{{ chartsData.users.title }}</div>
        <stackedLine :chartsData="chartsData" />
      </div>
    </div>

    <div class="df" style="width: 100%">
      <div>
        <div class="chart-title">{{ chartsData.average.title }}</div>
        <requestime :chartsData="chartsData" ref="requestimeRef" />
      </div>
      <div>
        <div class="chart-title">{{ chartsData.maxreq.title }}</div>
        <maximumreqtime :chartsData="chartsData" ref="maximumreqtimeRef" />
      </div>
    </div>
  </div>
</template>

<script setup>
import { getRunInfo } from '@/api/appv2/appv2';
import areachart from '@/components/AreaChart';
import stackedLine from '@/components/StackedLine';
import requestime from '@/components/RequestTime';
import maximumreqtime from '@/components/MaximumReqTime';

import { nextTick, ref, onUnmounted } from 'vue';

const requestimeRef = ref(null);
const maximumreqtimeRef = ref(null);
const areachartRef = ref(null);
const chartsData = ref({
  req: { title: '', series: {} },
  users: { title: '' },
  average: { title: '', series: {} },
  maxreq: { title: '', series: {} },
});

const fetchRunInfo = async () => {
  try {
    const res = await getRunInfo();
    if (res.code === 20000) {
      chartsData.value = res.data;
      nextTick(() => {
        // 更新图表数据而不是重新初始化
        if (areachartRef.value && areachartRef.value.updateChart) {
          areachartRef.value.updateChart(); // 假设你在 areachart 组件中实现了该方法
        }
        if (requestimeRef.value && requestimeRef.value.updateChart) {
          requestimeRef.value.updateChart(); // 更新 requestime 图表
        }
        if (maximumreqtimeRef.value && maximumreqtimeRef.value.updateChart) {
          maximumreqtimeRef.value.updateChart(); // 更新 maximumreqtime 图表
        }
      });
    }
  } catch (error) {
    console.log('error:', error);
  }
};

// 每 10 秒钟刷新一次数据
const timer = setInterval(fetchRunInfo, 10000);

fetchRunInfo();

// 清理定时器
onUnmounted(() => {
  clearInterval(timer);
});
</script>

<style lang="scss" scoped>
.chart-title {
  margin: 2vh 0 0 20px;
}
</style>
